import React, { useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import styles from './index.module.css'
import axios from 'axios'
import Nabar from '../../conpoment/Nabar'

const Index: React.FC = () => {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<'self' | 'insurance'>('self')

  // 从URL参数获取支付金额和项目数据
  const amountFromUrl = searchParams.get('amount')
  const itemsFromUrl = searchParams.get('items')
  const paymentAmount = amountFromUrl ? parseFloat(amountFromUrl) : 520.13
  const selectedItems = itemsFromUrl ? JSON.parse(decodeURIComponent(itemsFromUrl)) : []

  // 模拟数据
  const paymentData = {
    patientName: '王小柯',
    registrationNo: Date.now(),
    department: '门诊外一科',
    doctor: '刘医师',
    orderTime: '2020-01-01 10:20:36',
    orderNo: '2021010156256894',
    orderPlacementTime: '2020-01-01 10:23:36',
    paymentAmount: paymentAmount
  }

  const handlePaymentMethodChange = (method: 'self' | 'insurance') => {
    setSelectedPaymentMethod(method)
  }

  const handleConfirmPayment = async () => {
    try {
      console.log('确认缴费，支付方式:', selectedPaymentMethod)
      console.log('支付金额:', paymentAmount)
      console.log('选中项目:', selectedItems)
      
      // 发送支付请求
      const res = await axios.get('/api/pay', {
        params: {
          price: paymentAmount,
          id: paymentData.registrationNo,
          title: paymentData.department
        }
      })
      
      console.log('支付响应:', res.data)
      
      // 如果返回了支付链接，跳转到支付页面
      if (res.data && res.data.result) {
        // 在跳转前，将支付信息存储到localStorage
        const paymentInfo = {
          amount: paymentAmount,
          items: selectedItems,
          paymentMethod: selectedPaymentMethod,
          timestamp: new Date().toISOString()
        }
        localStorage.setItem('paymentInfo', JSON.stringify(paymentInfo))
        
        // 跳转到支付页面
        window.location.href = res.data.result
      } else {
        // 如果没有支付链接，直接模拟支付成功
        handlePaymentSuccess()
      }
      
    } catch (error) {
      console.error('支付请求失败:', error)
      alert('支付请求失败，请重试')
    }
  }

  // 处理支付成功
  const handlePaymentSuccess = () => {
    // 将支付信息存储到localStorage，供payment页面使用
    const paymentInfo = {
      amount: paymentAmount,
      items: selectedItems,
      paymentMethod: selectedPaymentMethod,
      timestamp: new Date().toISOString()
    }
    localStorage.setItem('paymentInfo', JSON.stringify(paymentInfo))
    
    // 跳转回缴费页面
    navigate('/payment')
  }

  return (
    <div className={styles.container}>
      {/* Header */}
    <Nabar title='确认缴费' sticky={false} />
      

      {/* Payment Information */}
      <div className={styles.infoCard}>
        <div className={styles.cardTitle}>缴费信息</div>
        <div className={styles.infoList}>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>就诊人:</span>
            <span className={styles.infoValue}>{paymentData.patientName}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>登记号:</span>
            <span className={styles.infoValue}>{paymentData.registrationNo}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>就诊科室:</span>
            <span className={styles.infoValue}>{paymentData.department}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>开单医生:</span>
            <span className={styles.infoValue}>{paymentData.doctor}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>开单时间:</span>
            <span className={styles.infoValue}>{paymentData.orderTime}</span>
          </div>
        </div>
      </div>
      {/* Order Information */}
      <div className={styles.infoCard}>
        <div className={styles.cardTitle}>订单信息</div>
        <div className={styles.infoList}>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>订单编号:</span>
            <span className={styles.infoValue}>{paymentData.orderNo}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>下单时间:</span>
            <span className={styles.infoValue}>{paymentData.orderPlacementTime}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>支付金额:</span>
            <span className={styles.paymentAmount}>¥{paymentData.paymentAmount.toFixed(2)}</span>
          </div>
        </div>
      </div>
      {/* Payment Method */}
      <div className={styles.infoCard}>
        <div className={styles.cardTitle}>支付方式</div>
        <div className={styles.paymentMethods}>
          <div 
            className={`${styles.paymentMethod} ${selectedPaymentMethod === 'self' ? styles.selected : ''}`}
            onClick={() => handlePaymentMethodChange('self')}
          >
            <div className={styles.methodInfo}>
              <div className={styles.methodName}>自费支付</div>
            </div>
            <div className={styles.radioButton}>
              {selectedPaymentMethod === 'self' && <div className={styles.radioSelected}></div>}
            </div>
          </div>
          <div 
            className={`${styles.paymentMethod} ${selectedPaymentMethod === 'insurance' ? styles.selected : ''}`}
            onClick={() => handlePaymentMethodChange('insurance')}
          >
            <div className={styles.methodInfo}>
              <div className={styles.methodName}>医保支付</div>
            </div>
            <div className={styles.radioButton}>
              {selectedPaymentMethod === 'insurance' && <div className={styles.radioSelected}></div>}
            </div>
          </div>
        </div>
      </div>

      {/* Confirm Payment Button */}
      <div className={styles.buttonContainer}>
        <button className={styles.confirmButton} onClick={handleConfirmPayment}>
          确认缴费
        </button>
      </div>
    </div>
  )
}


export default Index
